<?php
namespace OpenApi\Controller;
use Think\Controller;
//外部接口
class TestController extends Controller {
    public function _initialize(){
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }
	
	//接收订单
	public function order_bond(){
		// $param	= file_get_contents("php://input");
		// file_put_contents('./log/api/order_bond'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param='{
  "appkey": "test111",
  "timestamp": "1546485249932",
  "param": {
    "order_no": "19010002",
    "buyer_name": "邱运华",
    "buyer_phone": "18200968252",
    "buyer_idcard": "",
    "user_name": "邱运华",
    "user_phone": "18200968252",
    "user_idcard": "",
    "user_province": "广东省",
    "user_city": "惠州市",
    "user_area": "惠城区",
    "user_address": "惠环镇中星社区三坳岭新村盛和公？一楼",
    "order_amount": "0",
    "order_tax": "0.00",
    "discount": "",
    "order_insure": "0.00",
    "order_freight": "0.00",
    "trade_model": "",
    "remark": "",
    "apply_pay": "",
    "apply_logistics": "",
    "apply_order": null,
    "apply_list": "",
    "platform_name": "央广",
    "warehouse_code": "",
    "cod": "",
    "cod_money": "惠州市",
    "logiscompany_code": "",
    "logistics_no": "",
    "paycompany_code": "",
    "pay_number": "",
    "order_detail": [
      {
        "goods_sn": "851562031267",
        "goods_price": null,
        "goods_nums": 4.0,
        "goods_name": null
      }
    ]
  },
  "sign": "e0d943161570a804f4ddd7ae9294785a"
}';
		$param=json_decode($param,true);

		$app_key = $param['appkey'];
        $timestamp = $param['timestamp'];
        $get_sign = $param['sign'];
        if(is_array($param['param'])){
            $param = $param['param'];
        }else{
            $param = json_decode($param['param'],true);
        }
        // $app_secret='';
        switch ($app_key) {
        	case 'test111':
        		$app_secret = '123456';
        		break;
        	case 'PNZgKvQpKfnWitLg':
        		$app_secret = 'Q5BYL4osudAXrbvrfGMmR76I3SKQXSg7';
        		$info['user_code']='PN1MBDNQ3G';
				$info['user_key']='PN1MBDNQ3G';
				$info['merchant_code']='PN1MBDNQ3G';
        		break;
        }
        if(!$app_secret){
        	alert_json_new(0,'密钥参数错误');
        }

        if(!isset($param) || count($param)==0){
        	alert_json_new(0,'没有数据');
        }

        // if($timestamp*1<time()*1-10){
        // 	alert_json_new(0,'请求过期,请重新发起');
        // }

        $new_str = genVerify($param);
        $sign = md5($app_secret.'appkey'.$app_key.'param'.$new_str.'timestamp'.$timestamp.$app_secret);
        if($get_sign != $sign){
        	alert_json_new(0,'验签失败str:'.$new_str.';sign:'.$sign.';get_sign:'.$param['sign']);
        }

		//必传参数-订单表
        $must_param_order = ['order_no','buyer_name','buyer_phone','buyer_idcard','user_name','user_phone','user_province',
            'user_city','user_area','user_address','order_amount','order_tax','trade_model','apply_pay','apply_logistics',
            'apply_order','apply_list','platform_name','order_detail'];
        foreach ($must_param_order as $value){
            if(!isset($param[$value])){
                alert_json_new(0,'缺少订单参数：'.$value);
            }
        }

        //必传参数-产品表
        $must_param_goods = ['goods_sn','goods_price','goods_nums','goods_name'];
        foreach ($must_param_goods as $value){
            foreach ($param['order_detail'] as $k=>$good){
                if(!isset($good[$value])){
                    alert_json_new(0,'缺少产品参数：'.$value);
                }
                if(empty($good[$value])){
                	$msg['msg']='必传产品参数值不能为空';
                    alert_json_new(0,'缺少产品参数值：'.$value);
                }
            }
        }

        $vs = $param;
        $order_no = $vs['order_no'];
        alert_json_new(1,'订单'.$vs['order_no'].'基本信息测试成功,具体数据信息未验证');

		$return['flag']=1;
		$return['tip']="添加成功！";
		$return['data']=$data_info;
		$this->ajaxReturn($return);
	}
	
	//税金提示
	public function alert_tax(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/alert_tax.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		$u=M('User');
		$m=M('Member');
		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		$map['user_code']=$param['user_code'];
		$member_id=$u->where($map)->getField('member_id');
		$data_m['oms_fee_status']=$param['tax_status'];
		$res=$m->where(array('id'=>$member_id))->save($data_m);
		if($res!==false){
			$return['status']=1;
			$return['message']='成功';
			$this->ajaxReturn($return);
		}else{
			$return['status']=1;
			$return['message']='失败';
			$this->ajaxReturn($return);
		}
	}
	//订单状态接口
	public function order_status(){
		$u=M('User');
		$data=file_get_contents("php://input");
		file_put_contents('./log/order_status'.date('Y-m-d').'.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// $data='[{"user_code":"AO20170621","order_no":"JY-2024659","apply_order_no":"C20170719138139","logistics_no":"50552940008922","is_pass":0,"is_deliver":0,"platform_name":"ERP","fail_reason":"feifeifeif"}]';
        $param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['order_no']='';
			$this->ajaxReturn($return);
        }
		foreach($param as $k=>$v){
			$user_code=$v['user_code'];
			// $user_key=$v['user_key'];
			$map['old_order_no']=$v['order_no'];
			$map['status']=1;
			$data_pushorder=array();
			$data_pushorder['apply_order_no']=$v['apply_order_no'];
			$data_pushorder['logistics_no']=$v['logistics_no'];
			$data_pushorder['is_pass']=$v['is_pass'];
			$data_pushorder['is_delivery']=$v['is_deliver'];
			$data_pushorder['fail_reason']=$v['fail_reason'];
			$data_pushorder['actual_weight']=$v['actual_weight'];//实际重量
			if(empty($v['deliver_time'])){
				$data_pushorder['delivery_time']=0;//出库时间
			}else{
				$data_pushorder['delivery_time']=$v['deliver_time'];//出库时间
			}
			
			$u_info=$u->field('username')->where(array('user_code'=>$user_code))->find();
			$db_name=C('DB_PREFIX_T').$u_info['username'];
			C('db_config.DB_NAME',$db_name);
			$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
			$res=$m->where($map)->save($data_pushorder);
			// echo $m->getlastsql();
			// die;
			$return[$k]['order_no']=$v['order_no'];
			if($res===false){
				$return[$k]['status']=0;
			}else{
				//推送分销商-begin
				$m_info=$m->field('order_erp,agent_id')->where($map)->find();
				// echo $m->getlastsql();
				// die;
				$agent_id=$m_info['agent_id'];
				if(!empty($agent_id)){
					// $agent_url="http://erpvr.jm.com/index.php/Agent/Api/order_status";//分销订单状态接口
					$agent_url="http://www.t-cang.com/erpts/index.php/Agent/Api/order_status";
					$data_pushorder['order_no']=substr($v['order_no'],-14);//原订单号
					$data_pushorder['agent_id']=$agent_id;
					$res_agent = push($agent_url,$data_pushorder);
					$res_agent=json_decode($res_agent,true);
					if(!$res_agent['status']){
						file_put_contents('./log/order_status_agent.log',date('Y-m-d H:i:s').var_export($res_agent,true).PHP_EOL,FILE_APPEND);//日志导出sql
					}
				}
				//推送分销商-end
				//推送订单收集系统-begin
				$order_erp=$m_info['order_erp'];
				if(!empty($order_erp)){
					$agent_url="http://192.168.0.8:8080/com.botao.erp.api/orderDetails/receiveData.do";//抓单订单状态接口
					// $agent_url="http://www.t-cang.com/erpts/index.php/Agent/Api/order_status";
					$data_pushorder_ss=array();
					$data_pushorder_ss['logisticsId']=$v['logiscompany_code'];//物流企业编号
					$data_pushorder_ss['logisticsName']=$v['logiscompany_name'];//物流单号
					$data_pushorder_ss['waybill']=$v['logistics_no'];//物流单号
					if(empty($v['deliver_time'])){
						$data_pushorder_ss['deliveryTime']=0;//出库时间
					}else{
						$data_pushorder_ss['deliveryTime']=$v['deliver_time'];//出库时间
					}
					$data_pushorder_ss['orderId']=$v['order_no'];//原订单号
					$res_agent = pushjava($agent_url,$data_pushorder_ss);
					dump($res_agent);
					die;
					$res_agent=json_decode($res_agent,true);
					if(!$res_agent['status']){
						file_put_contents('./log/order_status_agent.log',date('Y-m-d H:i:s').var_export($res_agent,true).PHP_EOL,FILE_APPEND);//日志导出sql
					}
				}
				//推送订单收集系统-end
				$return[$k]['status']=1;
			}
		}
		$this->ajaxReturn($return);
	}
	
	//流水号
	public function serialNumber($tablename,$db_name){
		C('db_config.DB_NAME',$db_name);
		$m=M($tablename, C('DB_PREFIX_T'), C('db_config'));
		//当日流水号生成
		$map['_string']="add_time-UNIX_TIMESTAMP(DATE(NOW()))>0 and add_time-UNIX_TIMESTAMP(DATE(NOW()))<86400";
		$count=$m->where($map)->count();//当天添加的采购单数
		
		$count=$count+1;
		$serial_number="";
		if($count<10){
			$serial_number='0000'.strval($count);
		}
		if($count>=10 and $count<100){
			$serial_number='000'.$count;
		}
		if($count>=100 and $count<1000){
			$serial_number='00'.$count;
		}
		if($count>=1000 and $count<10000){
			$serial_number='0'.$count;
		}
		return $serial_number;//流水序号
	}
}